import React, { Component } from 'react'
import { withRouter } from 'react-router-dom'
import axios from 'axios'
import MyCarousel from './Carousel'
import AFQ from './AFQ'
import AttrList from './AttrList'
import store from '../../store/'
import { connect } from 'react-redux'

class ProductSection extends Component {
  state = {
    productId: '',
    carouselList: [],
    productDetail: [],
    newItemList: [],
  }
  addEventListenerBool = false
  refreshPage(id) {
    axios
      .get('item/detail?id=' + id)
      .then((res) => {
        const productDetail = JSON.parse(JSON.stringify(res.data.item))
        const carouselList = [
          productDetail.itemDetail.picUrl1,
          productDetail.itemDetail.picUrl2,
          productDetail.itemDetail.picUrl3,
          productDetail.itemDetail.picUrl4,
        ]
        this.setState({
          productDetail,
          carouselList,
        })
        /* redux */ 
        const skuSpecList = productDetail.skuSpecList.map((v) => {
         return {
           id: v.id,
          name: v.name,
          value: v.skuSpecValueList[0].value,
        }
        })
        let productInfo={
          showSkuSpecList: false,
          num: 1,
          SkuSpecList:[...skuSpecList],
          pic: productDetail.listPicUrl,
          name:productDetail.name,
          itemId:productDetail.id,
          price: productDetail.retailPrice,
          oldPrice:productDetail.counterPrice,
          checked:true,
          itemTag: productDetail.itemTagList.length? productDetail.itemTagList[0].name : ''
        }
        window.localStorage.setItem('productInfo',JSON.stringify(productInfo))
        this.props.changeProductReducer(['productInfo'], productInfo)
        /* redux */
      })
      .then(() => {
        const id = this.props.location.search.split('=')[1]
        var formData = new FormData()
        formData.append('id', id)
        axios({
          url: '/xhr/wapitem/rcmd.json',
          method: 'post',
          headers: { 'X-Requested-With': 'XMLHttpRequest' },
          data: formData,
        }).then((res) => {
          const arr = JSON.parse(JSON.stringify(res.data.data.items))
          this.setState({
            newItemList: [
              arr.slice(0, 2),
              arr.slice(2, 4),
              arr.slice(4, 6),
              arr.slice(6),
            ],
          })
        })
      })
  }
  componentDidMount() {
    const productId = Number(this.props.location.search.split('=')[1])
    this.refreshPage(productId)
    window.addEventListener('popstate', () => {
      this.goBackHandler()
    })
  }
  // 回到顶部函数
  goToBot() {
    if (this.addEventListenerBool) return
    if (this.state.newItemList.length) {
      this.addEventListenerBool = true
      const con = document.getElementsByClassName('ProductSection')[0]
      const toBotBtn = document.getElementsByClassName('m-goToBot')[0]
      const toBotTop = document.getElementsByClassName('m-goToTop')[0]
      toBotBtn.addEventListener(
        'click',
        this.goBotBtnClickHandler.bind(this, con)
      )
      toBotTop.addEventListener(
        'click',
        this.goTopBtnClickHandler.bind(this, con)
      )
    }
  }
  goBotBtnClickHandler(con) {
    var timer = setInterval(() => {
      con.scrollTop += 300
      if (
        con.scrollTop >=
        con.children[0].offsetHeight - con.offsetHeight - 300
      ) {
        con.scrollTop = con.children[0].offsetHeight - con.offsetHeight
        clearInterval(timer)
      }
    }, 16)
  }
  goTopBtnClickHandler(con) {
    var timer = setInterval(() => {
      con.scrollTop -= 300
      if (con.scrollTop < 300) {
        con.scrollTop = 0
        clearInterval(timer)
      }
    }, 16)
  }
  // 重新刷新页面
  goBackHandler() {
    window.location.reload()
  }
  render() {
    this.goToBot()
    const { productDetail, carouselList, newItemList } = this.state
    if (carouselList.length) {
      let productInfo = store
        .getState()
        .getIn(['productReducer', 'productInfo'])
      return (
        <div className="ProductSection">
          <div  style={{ display: !productInfo.showSkuSpecList ? 'block' : 'none' }}> {/* 主体开始 */}
          {!carouselList.length ? (
            ''
          ) : (
            <div>
              {/* 轮播图开始 */}
              <MyCarousel carouselList={carouselList}></MyCarousel>
              {/* 轮播图结束 */}
              {productDetail.featuredSeries && (
                <img
                  key="0"
                  src={productDetail.featuredSeries.detailPicUrl}
                  alt=""
                />
              )}
              {/* 商品描述 价格 开始 */}
              <div className="productInfo">
                <div className="productPrice">
                  <span className="productCurrentPrice">
                    ¥{productDetail.retailPrice}
                  </span>
                  <small className="productPriPrice">
                    {productDetail.counterPrice &&
                      '¥' + productDetail.counterPrice }
                  </small>
                </div>
                <div className="productTagList">
                  {productDetail.itemTagList.map((v) => (
                    <span key={v.tagId}>{v.name}</span>
                  ))}
                </div>
                <div className="spmcBanner">
                  <div className="spmcPrice">
                    <span className="spmcDiscount">天天免邮</span>
                    <span className="spmcDesc">
                      Pro会员立享免邮，到手价
                      <span className="spmcEconomizePrice">
                        {(productDetail.retailPrice * 0.9).toFixed(2)}
                      </span>
                    </span>
                    <i className="u-icon u-icon-questionMark"></i>
                  </div>
                  <span className="spmcBtn">开通</span>
                </div>
                <div className="baseInfo">
                  <div className="info">
                    <div className="name">{productDetail.name}</div>
                    <div className="desc">推荐理由</div>
                  </div>
                  <div className="comment single-line">
                    <div className="wrap">
                      <div className="info-wrap">
                        <div className="num">
                          {productDetail.goodCmtRate || '98%'}
                        </div>
                        <div className="com">好评率</div>
                      </div>
                      <i className="icon u-icon u-address-right"></i>
                    </div>
                  </div>
                </div>
                <div className="rcmdBanner">
                  <div className="angleTop">
                    <span className="angleContent"></span>
                  </div>
                  <ul>
                    {productDetail.recommendReason &&
                      productDetail.recommendReason.map((val, i) => (
                        <li key={val}>
                          <div className="key">{i + 1}</div>
                          <div className="recommendReason">{val}</div>
                        </li>
                      ))}
                  </ul>
                </div>
              </div>
              {/* 商品描述 价格 结束 */}
              {/* 商品参数开始 */}
              <AttrList productDetail={productDetail}></AttrList>
              {/* 商品参数结束 */}
              {/* 商品图片展示开始 */}

              <div
                dangerouslySetInnerHTML={{
                  __html: productDetail.itemDetail.detailHtml,
                }}
              ></div>

              {/* 商品图片展示结束 */}

              {/* 常见问题开始 */}
              <div className="lovingGoodTit">
                <div className="itemLine"></div>
                <span className="itemText">常见问题</span>
              </div>
              <AFQ></AFQ>
              {/* 常见问题结束 */}
              {/* 猜你喜欢开始 */}
              <div>
                <div className="lovingGoodTit">
                  <div className="itemLine"></div>
                  <span className="itemText">你可能还喜欢</span>
                </div>
                {newItemList &&
                  newItemList.map((item, i) => (
                    <div className="NewItemList" key={i}>
                      {item.map((v, i) => (
                        <div
                          className="NewItemListItem"
                          key={v.displaySkuId}
                          onClick={() => {
                            // console.log(v.id);
                            this.props.history.push(
                              '/ProductDetail/?id=' + v.id
                            )
                          }}
                        >
                          <img src={v.primaryPicUrl} alt="" />
                          <div className="newItemTitle">{v.name}</div>
                          <div className="newItemPrice">¥{v.retailPrice}</div>
                          <div className="newItemTag">
                            {v.itemTagList &&
                              v.itemTagList.map((val, i) => (
                                <span key={val.name + val.tagId}>
                                  {val.name}
                                </span>
                              ))}
                          </div>
                        </div>
                      ))}
                    </div>
                  ))}
              </div>
              {/* 猜你喜欢结束 */}
              {/* 主体结束 */}
            </div>
          )}
          {/* 回到顶部开始 */}
          <i className="m-goToTop"></i>
          <i className="m-goToBot"></i>
          {/* 回到顶部结束 */}</div>
         
          <div
            className="skuSpecList"
            style={{ display: productInfo.showSkuSpecList ? 'block' : 'none' }}
          >
            {/* 规格框开始 */}
            <div className="info-con">
              <div className="left f-fl">
                <img src={productDetail.listPicUrl}  alt=''/>
              </div>
              <div className="right f-fl">
                <div className="con">
                  <span className="tag w-tag w-tag-yellow">
                    {productDetail.itemTagList.length
                      ? productDetail.itemTagList[0].name
                      : '特价'}
                  </span>
                  <p className="price">
                    <span>
                      <span>价格：¥{productDetail.retailPrice}</span>
                      <span className="nowPrice">
                        ¥{productDetail.counterPrice}
                      </span>
                    </span>
                  </p>
                  <p className="sku">
                    已选择：
                    {this.props.productInfo.SkuSpecList.length &&
                      this.props.productInfo.SkuSpecList.map((v, i) => (
                        <span className="it" key={v.value}>
                          {v.value}
                        </span>
                      ))}
                  </p>
                </div>
              </div>
            </div>
            {/* 选择框 */}
            <div className="spec-con">
              <div>
                {productDetail.skuSpecList.map((v, i) => (
                  <div className="u-format" key={v.id}>
                    <div className="tt">{v.name}</div>
                    <div className="con">
                      {v.skuSpecValueList.map((val) => (
                        <div
                          className={
                            this.props.productInfo.SkuSpecList.length &&
                            this.props.productInfo.SkuSpecList[i].value ===
                              val.value
                              ? 'tab active'
                              : 'tab'
                          }
                          onClick={() => {
                            let arr = [...this.props.productInfo.SkuSpecList]
                            arr[i].value = val.value
                            this.props.changeSkuSpecList(arr)
                          }}
                          key={val.id}
                        >
                          <span className="tab-txt">{val.value}</span>
                        </div>
                      ))}
                    </div>
                  </div>
                ))}
              </div>
              <div className="u-format">
                <div className="tt">数量</div>
                <div className="con m-selNumRow">
                  <div className="m-selnum dl">
                    <i
                      className="less z-dis"
                      onClick={(e) => {
                        if (this.props.productInfo.num <= 1) return
                        this.props.changeNum(this.props.productInfo.num - 1)
                      }}
                    >
                      -
                    </i>
                    <div className="textWrap">
                      <input
                        type="tel"
                        value={this.props.productInfo.num}
                        onChange={(e) => {
                          this.props.changeNum(
                            Number(e.target.value.replace(/[^0-9]/g, ''))
                          )
                        }}
                      />
                    </div>
                    <div
                      className="more"
                      onClick={() => {
                        this.props.changeNum(this.props.productInfo.num + 1)
                      }}
                    >
                      +
                    </div>
                  </div>
                </div>
              </div>
            </div>

            {/* 规格框结束 */}
          </div>
        </div>
      )
    } else {
      return <div className="ProductSection"></div>
    }
  }
}
const mapStateToProps = (state) => {
  return {
    productInfo: state.getIn(['productReducer', 'productInfo']),
  }
}
const mapDispatchToProps = (dispatch) => {
  return {
    changeNum: (step) => {
      let action = (step) => {
        return {
          type: 'CHANGE_NUM',
          payload: step,
        }
      }
      dispatch(action(step))
    },
    changeSkuSpecList: (skuSpecList) => {
      let action = (skuSpecList) => {
        return {
          type: 'CHANGE_SKU_LIST',
          payload: skuSpecList,
        }
      }
      dispatch(action(skuSpecList))
    },
    /* 结束 */
    changeProductReducer: (arr, val) => {
      let action = (arr, val) => {
        return {
          type: 'UPDATE_PRODUCT_DETAIL',
          payload: {
            keyArr: arr,
            val: val,
          },
        }
      }
      dispatch(action(arr, val))
    },
  }
}
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(ProductSection))
